package com.etrans.util.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

public class WaitLock {

	private final static Logger logger = Logger.getLogger(WaitLock.class);
	private final Lock lock;
	private final Condition condition;

	public WaitLock() {
		lock = new ReentrantLock();
		condition = lock.newCondition();
	}

	public WaitLock(Lock lock) {
		if (lock == null) {
			lock = new ReentrantLock();
		}

		this.lock = lock;
		condition = lock.newCondition();
	}

	public boolean waitFor(long timeout) {
		lock.lock();
		try {
			condition.await(timeout, TimeUnit.MILLISECONDS);
			return true;
		} catch (InterruptedException e) {
			logger.warn("fail to go in to wait-timeout status", e);
			return false;
		} finally {
			lock.unlock();
		}
	}

	public boolean waitFor() {
		lock.lock();
		try {
			condition.await();
			return true;
		} catch (InterruptedException e) {
			logger.warn("fail to go in to wait status", e);
			return false;
		} finally {
			lock.unlock();
		}
	}

	public void wake() {
		lock.lock();
		try {
			condition.signal();
		} finally {
			lock.unlock();
		}
	}

	public void wakeAll() {
		lock.lock();
		try {
			condition.signalAll();
		} finally {
			lock.unlock();
		}
	}

}
